package com.jcli.novel_t;

import com.jcli.novel_t.exception.FileProcessingException;

import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 进阶版
 * 1.优化异常处理，更友好的错误提示信息或者将异常传播给调用方处理。
 * 2.处理魔法字符串：将这些字符串提取成常量或配置参数。
 * 3.文件路径拼接: 使用java.nio.file.Path来处理文件路径，以确保在不同操作系统上都能正确工作，而不仅仅是使用File.separator。
 * 例如，Paths.get(outputDirectory, fileName + ".txt")。
 * 4.将这些配置参数提取到外部属性文件中。
 * 5.日志未添加。
 */


public class TextFileProcessor01 {
    private Properties properties;

     public TextFileProcessor01(Properties properties) {
        this.properties = properties;
    }

    public void processTextFile(String inputFilePath, String outputDirectory, String outputFilePath2, String outputFilePath3) throws FileProcessingException {
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
            // 读取第一行文本
            String firstLine = reader.readLine();
            if (firstLine != null) {
                // 找到第二个空格前的所有数据作为文件名
                int firstSpaceIndex = firstLine.indexOf(' ');
                if (firstSpaceIndex != -1) {
                    int secondSpaceIndex = firstLine.indexOf(' ', firstSpaceIndex + 1);
                    if (secondSpaceIndex != -1) {
                        String fileName = firstLine.substring(1, secondSpaceIndex);//一个空格一个文件
                        // 构建输出文件路径
                        // String outputFilePath1 = outputDirectory + File.separator + fileName + ".txt";
                        //文件拼接，能在其他平台通用
                        String outputFilePath1 = Paths.get(outputDirectory, fileName + ".txt").toString();
                        try (BufferedWriter writer1 = new BufferedWriter(new FileWriter(outputFilePath1));
                             BufferedWriter writer2 = new BufferedWriter(new FileWriter(outputFilePath2));
                             BufferedWriter writer3 = new BufferedWriter(new FileWriter(outputFilePath3, true))) {

                            // 处理文件的其余部分
                            writer1.write(processLine(firstLine));
                            writer1.newLine();

                            writer2.write(firstLine);
                            writer2.newLine();

                            writer3.write(processLine(firstLine));
                            writer3.newLine();

                            String line;
                            while ((line = reader.readLine()) != null) {
                                String processedLine = processLine(line);
                                writer1.write(processedLine);
                                writer1.newLine();

                                writer2.write(line);
                                writer2.newLine();

                                writer3.write(processedLine);
                                writer3.newLine();
                            }
                        }
                        System.out.println("替换后的文件已保存在：" + outputFilePath1);
                    }
                }
            }
        } catch (IOException e) {
            throw new FileProcessingException("文件处理出错: " + e.getMessage());
        }
    }

    private String processLine(String line) {
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            String escapedKey = Pattern.quote(key);

            // 检查行是否包含键，如果包含则进行替换
            if (line.contains(key)) {
                line = line.replaceAll(escapedKey, value);
            }
        }
        return line;
    }

    public static void main(String[] args) {
        Properties defaultProperties = new Properties();
        Properties customProperties = new Properties();

        try (InputStream defaultInputStream = new FileInputStream("src/main/resources/config.properties");
             InputStream customInputStream = new FileInputStream("app.properties")) {
            defaultProperties.load(new InputStreamReader(defaultInputStream, "UTF-8"));
            customProperties.load(new InputStreamReader(customInputStream, "UTF-8"));
        } catch (IOException e) {
            System.err.println("无法加载配置文件: " + e.getMessage());
            return;
        }
        // 合并两个配置文件的内容
        Properties mergedProperties = new Properties();
        mergedProperties.putAll(defaultProperties);
        mergedProperties.putAll(customProperties);
        TextFileProcessor01 processor = new TextFileProcessor01(mergedProperties);
        try {
            processor.processTextFile(
                    mergedProperties.getProperty("inputFilePath"),
                    mergedProperties.getProperty("outputDirectory"),
                    mergedProperties.getProperty("outputFilePath2"),
                    mergedProperties.getProperty("outputFilePath3"));
        } catch (FileProcessingException e) {
            System.err.println("文件处理出错: " + e.getMessage());
        }
    }
}
